package tailfile

import (
	"Logger/logAgent/collect"
	"Logger/logAgent/etcd"
	"context"
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"go.etcd.io/etcd/api/v3/mvccpb"
)

type tailManger struct {
	taskMap map[string]*TailTask
}

var tailMgr *tailManger

func (t *tailManger) updateConf(collects collect.Collections) {
	//新增
	for _, col := range collects {
		_, ok := t.taskMap[col.Topic]
		if !ok {
			task, _ := newTailTask(col.Topic, col.Path)
			tailMgr.taskMap[col.Topic] = task
			go task.run()
		}
	}

	//减少
	for topic, _ := range t.taskMap {
		var found bool
		for _, collection := range collects {
			if collection.Topic == topic {
				found = true
				break
			}
		}
		//如果新配置中没有
		if !found {
			t.taskMap[topic].cancel()
			delete(t.taskMap, topic)
		}
	}
}

func (t *tailManger) delConf() {
	for _, tsk := range t.taskMap {
		tsk.cancel()
	}
	t.taskMap = make(map[string]*TailTask)
}

func Init(collections collect.Collections) error {
	tailMgr = &tailManger{
		taskMap: make(map[string]*TailTask),
	}
	for _, collection := range collections {
		task, err := newTailTask(collection.Topic, collection.Path)
		if err != nil {
			return err
		}
		tailMgr.taskMap[collection.Topic] = task
		go task.run()
	}
	return nil
}

func Watch(key string) {
	watchChan := etcd.Cli.Watch(context.Background(), key)
	for wrsp := range watchChan {
		for _, ev := range wrsp.Events {
			fmt.Printf("Type:%v Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
			switch ev.Type {
			case mvccpb.PUT:
				var colls collect.Collections
				err := json.Unmarshal(ev.Kv.Value, &colls)
				if err != nil {
					logrus.Warning(err.Error())
					continue
				}
				tailMgr.updateConf(colls)
			case mvccpb.DELETE:
				tailMgr.delConf()
			}
		}
	}
}
